package com.mondari.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
public class ResponseUtil {

    public static void write(HttpServletResponse response, String filePath, String fileName) throws IOException {
        UrlResource urlResource = new UrlResource(ResourceUtils.FILE_URL_PREFIX + filePath);
        response.reset(); // 非常重要
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" +
                URLEncoder.encode(fileName == null ? "" : fileName, StandardCharsets.UTF_8.name()));
        response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setContentLengthLong(urlResource.getFile().length());
        FileCopyUtils.copy(urlResource.getInputStream(), new BufferedOutputStream(response.getOutputStream()));
    }

    public static void writeQuietly(HttpServletResponse response, String filePath, String fileName) {
        try {
            write(response, filePath, fileName);
        } catch (IOException e) {
            // nothing to do
            log.error("failed to invoke 'writeQuietly' method", e);
        }
    }
}
